package com.hngates.architecture.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hngates.architecture.domain.ArcLabourSubCompany;
import com.hngates.architecture.domain.ArcProject;
import com.hngates.architecture.domain.ArcWorkerComplain;
import com.hngates.architecture.domain.vo.ComplainPersonVO;
import com.hngates.architecture.domain.vo.ComplainTeamVO;
import com.hngates.architecture.service.*;
import com.hngates.common.annotation.Log;
import com.hngates.common.constant.Constants;
import com.hngates.common.core.controller.BaseController;
import com.hngates.common.core.domain.AjaxResult;
import com.hngates.common.core.page.TableDataInfo;
import com.hngates.common.enums.BusinessType;
import com.hngates.common.utils.poi.ExcelUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工人投诉具体情况Controller
 *
 * @author jwhe
 * @date 2022-07-05
 */
@Controller
@RequestMapping("/architecture/complain")
public class ArcWorkerComplainController extends BaseController {
    private String prefix = "architecture/complain";

    @Autowired
    private IArcWorkerComplainService arcWorkerComplainService;
    @Autowired
    private IArcProjectService arcProjectService;
    @Autowired
    private IArcBuilderCompanyService arcBuilderCompanyService;
    @Autowired
    private IArcConstructContractService arcConstructContractService;
    @Autowired
    private IArcLabourCompanyService arcLabourCompanyService;
    @Autowired
    private IArcLabourContractService arcLabourContractService;
    @Autowired
    private IArcLabourSubCompanyService arcLabourSubCompanyService;
    @Autowired
    private IArcLabourSubCompanyDetailsService arcLabourSubCompanyDetailsService;
    @Autowired
    private IArcProjectBuilderRelService arcProjectBuilderRelService;

    @RequiresPermissions("architecture:complain:view")
    @GetMapping()
    public String complain(ModelMap modelMap) {
        ArcProject arcProject = new ArcProject();
        arcProject.setDelFlag(Constants.DEl_FLAG_0);
        List<ArcProject> arcProjects = arcProjectService.selectArcProjectList(arcProject);

        ArcLabourSubCompany arcLabourSubCompany = new ArcLabourSubCompany();
        arcLabourSubCompany.setDelFlag(Constants.DEl_FLAG_0);
        List<ArcLabourSubCompany> arcLabourSubCompanies = arcLabourSubCompanyService.selectArcLabourSubCompanyList(arcLabourSubCompany);

        modelMap.put("projects", arcProjects);
        modelMap.put("labourSubs", arcLabourSubCompanies);

        return prefix + "/complain";
    }

    /**
     * 查询工人投诉具体情况列表
     */
    @RequiresPermissions("architecture:complain:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ArcWorkerComplain arcWorkerComplain) {
        startPage();
        List<ArcWorkerComplain> list = arcWorkerComplainService.selectArcWorkerComplainList(arcWorkerComplain);
        return getDataTable(list);
    }

    /**
     * 导出工人投诉具体情况列表
     */
    @RequiresPermissions("architecture:complain:export")
    @Log(title = "工人投诉具体情况", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ArcWorkerComplain arcWorkerComplain) {
        List<ArcWorkerComplain> list = arcWorkerComplainService.selectArcWorkerComplainList(arcWorkerComplain);
        ExcelUtil<ArcWorkerComplain> util = new ExcelUtil<ArcWorkerComplain>(ArcWorkerComplain.class);
        return util.exportExcel(list, "工人投诉具体情况数据");
    }

    /**
     * 新增工人投诉具体情况
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存工人投诉具体情况
     */
    @RequiresPermissions("architecture:complain:add")
    @Log(title = "工人投诉具体情况", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ArcWorkerComplain arcWorkerComplain) {
        return toAjax(arcWorkerComplainService.insertArcWorkerComplain(arcWorkerComplain));
    }

    /**
     * 修改工人投诉具体情况
     */
    @RequiresPermissions("architecture:complain:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        ArcWorkerComplain arcWorkerComplain = arcWorkerComplainService.selectArcWorkerComplainById(id);
        mmap.put("arcWorkerComplain", arcWorkerComplain);
        return prefix + "/edit";
    }

    /**
     * 修改保存工人投诉具体情况
     */
    @RequiresPermissions("architecture:complain:edit")
    @Log(title = "工人投诉具体情况", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ArcWorkerComplain arcWorkerComplain) {
        return toAjax(arcWorkerComplainService.updateArcWorkerComplain(arcWorkerComplain));
    }

    /**
     * 删除工人投诉具体情况
     */
    @RequiresPermissions("architecture:complain:remove")
    @Log(title = "工人投诉具体情况", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(arcWorkerComplainService.deleteArcWorkerComplainByIds(ids));
    }

    @GetMapping("/excelTeamTpl")
    @ResponseBody
    public AjaxResult excelTeamTpl() {
        String fileName = "template/投诉信息模板-集体.xlsx";
        return AjaxResult.success(fileName);
    }

    private String rex = "\\d+";
    private Pattern pattern = Pattern.compile(rex);

    private int getNumber(String str) {
        int x = 0;
        try {
            Matcher matcher = pattern.matcher(str);
            if (matcher.find()) {
                String group = matcher.group(0);
                x = Integer.parseInt(group);
            } else {
                if (StrUtil.contains(str, "、")) {
                    x = StrUtil.split(str, "、").size();
                } else if (StrUtil.contains(str, ",")) {
                    x = StrUtil.split(str, ",").size();
                } else if (!StrUtil.isEmpty(str)) {
                    x = 1;
                }
            }
        } catch (Exception e) {
            logger.error(str + "解析数字时异常", e);
        }
        return x;
    }

    @PostMapping("/importTeam")
    @ResponseBody
    public AjaxResult importInfoTeam(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<ComplainTeamVO> util = new ExcelUtil<>(ComplainTeamVO.class);
        List<ComplainTeamVO> teams = util.importExcel(file.getInputStream(), 1);
        //同一个在同一工地投诉过同一公司就算投诉过，执行更新
        if (teams == null || teams.isEmpty()) {
            return AjaxResult.success("ok");
        }
        for (ComplainTeamVO team : teams) {
            String projectName = team.getComplainProjectName();
            ArcProject project = arcProjectService.selectArcProjectByName(projectName);

            if (project == null) {
                continue;
            }
            String labourSubCompanyName = team.getComplainLabourSubCompanyName();
            ArcLabourSubCompany arcLabourSubCompany = arcLabourSubCompanyService.selectArcLabourSubCompanyByName(labourSubCompanyName);
            Long subCompanyId = arcLabourSubCompany == null ? null : arcLabourSubCompany.getId();

            ArcWorkerComplain complain = new ArcWorkerComplain();
            complain.setAmountInvolved(team.getAmountInvolved())
                    .setComplainLeader(team.getComplainLeader())
                    .setComplainMember(team.getComplainMember())
                    .setComplainType("集体")
                    .setSubLabourId(subCompanyId)
                    .setProjectId(project.getId())
                    .setComplainContent(team.getComplainContent())
                    .setComplainDepartment(team.getComplainDepartment())
                    .setComplainTime(team.getComplainTime())
                    .setComplainNumber(getNumber(team.getComplainMember()))
            ;
            if (complain.getComplainNumber() > 0 && complain.getComplainNumber() <= 3) {
                complain.setComplainScore(5);
            } else if (complain.getComplainNumber() > 3 && complain.getComplainNumber() <= 10) {
                complain.setComplainScore(10);
            } else if (complain.getComplainNumber() > 10) {
                complain.setComplainScore(15);
            } else {
                complain.setComplainScore(0);
            }


            ArcWorkerComplain queryArgs = new ArcWorkerComplain();
            queryArgs.setComplainType("集体");
            queryArgs.setComplainLeader(team.getComplainLeader());
            queryArgs.setProjectId(project.getId());
            queryArgs.setSubLabourId(subCompanyId);
            List<ArcWorkerComplain> arcWorkerComplains = arcWorkerComplainService.selectArcWorkerComplainList(queryArgs);

            if (arcWorkerComplains != null && !arcWorkerComplains.isEmpty()) {
                if (updateSupport) {
                    ArcWorkerComplain arcWorkerComplain = arcWorkerComplains.get(0);
                    BeanUtil.copyProperties(complain, arcWorkerComplain);
                    arcWorkerComplainService.updateArcWorkerComplain(arcWorkerComplain);
                }
            } else {
                arcWorkerComplainService.insertArcWorkerComplain(complain);
            }
        }
        return AjaxResult.success("ok");
    }


    @GetMapping("/excelPersonTpl")
    @ResponseBody
    public AjaxResult excelPersonTpl() {
        String fileName = "template/投诉信息模板-个人.xlsx";
        return AjaxResult.success(fileName);
    }

    @PostMapping("/importPerson")
    @ResponseBody
    public AjaxResult importInfoPerson(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<ComplainPersonVO> util = new ExcelUtil<>(ComplainPersonVO.class);
        List<ComplainPersonVO> persons = util.importExcel(file.getInputStream(), 1);
        //同一个在同一工地投诉过同一公司就算投诉过，执行更新
        if (persons == null || persons.isEmpty()) {
            return AjaxResult.success("ok");
        }
        for (ComplainPersonVO person : persons) {
            String projectName = person.getComplainProjectName();
            ArcProject project = arcProjectService.selectArcProjectByName(projectName);
            if (project == null) {
                continue;
            }
            String labourSubCompanyName = person.getComplainLabourSubCompanyName();
            ArcLabourSubCompany arcLabourSubCompany = arcLabourSubCompanyService.selectArcLabourSubCompanyByName(labourSubCompanyName);

            Long subCompanyId = arcLabourSubCompany == null ? null : arcLabourSubCompany.getId();

            ArcWorkerComplain complain = new ArcWorkerComplain();
            complain.setAmountInvolved(person.getAmountInvolved())
                    .setComplainLeader(person.getComplainUserName())
                    .setComplainType("个人")
                    .setSubLabourId(subCompanyId)
                    .setProjectId(project.getId())
                    .setComplainContent(person.getComplainContent())
                    .setComplainDepartment(person.getComplainDepart())
                    .setComplainTime(person.getComplainTime())
                    .setComplainNumber(1)
                    .setComplainScore(5)
            ;

            ArcWorkerComplain queryArgs = new ArcWorkerComplain();
            queryArgs.setComplainType("个人");
            queryArgs.setComplainLeader(person.getComplainUserName());
            queryArgs.setProjectId(project.getId());
            queryArgs.setSubLabourId(subCompanyId);
            List<ArcWorkerComplain> arcWorkerComplains = arcWorkerComplainService.selectArcWorkerComplainList(queryArgs);

            if (arcWorkerComplains != null && !arcWorkerComplains.isEmpty()) {
                if (updateSupport) {
                    ArcWorkerComplain arcWorkerComplain = arcWorkerComplains.get(0);
                    BeanUtil.copyProperties(complain, arcWorkerComplain);
                    arcWorkerComplainService.updateArcWorkerComplain(arcWorkerComplain);
                }
            } else {
                arcWorkerComplainService.insertArcWorkerComplain(complain);
            }
        }


        return AjaxResult.success("ok");
    }
}
